/**
 * Project Name:九色鹿
 * File Name:OneKeyService.java
 * Package Name:com.fxp.project.jiuselu.onekey
 * Date:2020年04月02日 0:32
 * Copyright (c) 2020, Jason.Wang All Rights Reserved.
 */
package com.fxp.project.jiuselu.onekey;

import com.alibaba.fastjson.JSONObject;
import com.fxp.project.jiuselu.commons.http.HttpRestTools;
import com.fxp.project.jiuselu.commons.md5.Md5Util;
import com.fxp.project.jiuselu.onekey.utils.aes.AESUtils;
import com.fxp.project.jiuselu.onekey.utils.rsa.RSAUtils;
import com.fxp.project.jiuselu.onekey.utils.sign.SignUtils;
import lombok.Data;
import lombok.extern.log4j.Log4j2;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * ClassName:OneKeyService<br/>
 * Function: 一键登录的功能<br/>
 * Date:2020年04月02日 0:32<br/>
 *
 * @author Jason.Wang
 * @version 1.0.0.0
 * @see
 * @since JDK1.8
 */
@Data
@Log4j2
@Component
@ConfigurationProperties(prefix = OneKeyService.ID_PREFIX)
public class OneKeyService {

    public static final String ID_PREFIX = "sms.253.flash";

    /**
     * 创建应用时填写的RAS公私钥对
     */
    private String privateKey;
    /**
     * 加密方式 返回的手机号码加密方式，值包含：0（AES加密）、1（RSA加密）缺省为0，如使用RSA方式则在创建应用时必须填写RSA公钥。
     */
    private String encryptType;
    /**
     * 账户Id
     */
    private String appId;
    /**
     * 账户密码
     */
    private String appKey;


    /**
     * 解密手机号码
     */
    private String MOBILE_QUERY_URL = "https://api.253.com/open/flashsdk/mobile-query";
    /**
     * 验证手机号码
     */
    private String MOBILE_VALIDATE_URL = "https://api.253.com/open/flashsdk/mobile-validate";

    /**
     * queryMobile: 根据客户端传递的Token获取手机号<br/>
     *
     * @param token
     * @return
     * @author Jason.Wang
     * @createTime 2020/4/2 1:30
     */
    public String queryMobile(String token) {
        try {
            Map<String, String> params = new HashMap<>();
            params.put("token", token);
            params.put("appId", getAppId());
            //可以不传，不传则解密直接使用AES解密
            params.put("encryptType", getEncryptType() + "");
            params.put("sign", SignUtils.getSign(params, getAppKey()));
            JSONObject jsonObject = HttpRestTools.postForEntityForm(MOBILE_QUERY_URL, params, JSONObject.class);
            if (null != jsonObject) {
                jsonObject = JSONObject.parseObject(jsonObject.toJSONString());
                log.info("response:" + jsonObject.toJSONString());
                //返回码 200000为成功
                String code = jsonObject.getString("code");
                //返回消息
                String message = jsonObject.getString("message");
                //是否收费
                String chargeStatus = jsonObject.getString("chargeStatus");
                log.info("当前能正常进入到成功操作吗？：{}", "200000".equals(code) ? "能" : "不能");
                if ("200000".equals(code) && jsonObject.containsKey("data")) {
                    String dataStr = jsonObject.getString("data");
                    log.info("获取的Data为：{}", dataStr);

                    JSONObject dataObj = JSONObject.parseObject(dataStr);
                    String mobile = dataObj.getString("mobileName");
                    //交易流水号
                    String tradeNo = dataObj.getString("tradeNo");
                    log.info("当前加密方式为：{}", "0".equals(getEncryptType()) ? "AES" : "RSA");
                    if ("0".equals(getEncryptType())) {
                        String key = Md5Util.md5(getAppKey());
                        mobile = AESUtils.decrypt(mobile, key.substring(0, 16), key.substring(16));
                    } else if ("1".equals(getEncryptType())) {
                        mobile = RSAUtils.decryptByPrivateKeyForLongStr(mobile, getPrivateKey());
                    }
                    log.info("解密手机号为：{}", mobile);
                    return mobile;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * validateMobile: 根据客户端传递的Token、Mobile验证是否一致<br/>
     *
     * @param token
     * @param mobile
     * @return
     * @author Jason.Wang
     * @createTime 2020/4/2 1:31
     */
    public boolean validateMobile(String token, String mobile) {
        try {
            Map<String, String> params = new HashMap<>();
            params.put("token", token);
            params.put("appId", getAppId());
            params.put("mobile", mobile);
            params.put("sign", SignUtils.getSign(params, getAppKey()));
            JSONObject jsonObject = HttpRestTools.postForEntityForm(MOBILE_VALIDATE_URL, params, JSONObject.class);
            if (null != jsonObject) {
                jsonObject = JSONObject.parseObject(jsonObject.toJSONString());
                log.info("response:" + jsonObject.toJSONString());
                //返回码 200000为成功
                String code = jsonObject.getString("code");
                //返回消息
                String message = jsonObject.getString("message");
                //是否收费
                String chargeStatus = jsonObject.getString("chargeStatus");
                if ("200000".equals(code)) {
                    String dataStr = jsonObject.getString("data");
                    JSONObject dataObj = JSONObject.parseObject(dataStr);
                    String isVerify = dataObj.getString("isVerify");
                    //交易流水号
                    String tradeNo = dataObj.getString("tradeNo");
                    return "1".equals(isVerify);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}
